#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据库初始化脚本 - 修复版本
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from database import db
from app import app
from models.admin import Admin
from models.user import User
from models.table import BilliardTable
from models.staff import Staff
from datetime import datetime

def init_database():
    """初始化数据库"""
    with app.app_context():
        try:
            print("正在处理数据库初始化...")
            
            # 禁用外键检查
            with db.engine.connect() as conn:
                conn.execute(db.text('SET FOREIGN_KEY_CHECKS = 0'))
                conn.commit()
            
            print("正在删除所有表...")
            db.drop_all()
            
            print("正在创建所有表...")
            db.create_all()
            
            # 启用外键检查
            with db.engine.connect() as conn:
                conn.execute(db.text('SET FOREIGN_KEY_CHECKS = 1'))
                conn.commit()
            
            print("正在创建默认管理员账户...")
            admin = Admin(username='admin', name='系统管理员')
            admin.password = 'admin123'  # 使用属性设置器
            db.session.add(admin)
            
            print("正在创建测试台球桌...")
            tables = [
                BilliardTable(
                    table_no='T001',
                    table_name='九球桌1号',
                    table_type='nine_ball',
                    size='9ft',
                    brand='星牌',
                    area='A区',
                    floor=1,
                    position='靠窗位置',
                    hourly_rate=60.00,
                    member_rate=42.00,
                    peak_rate=80.00,
                    has_lighting=True,
                    has_scoreboard=True
                ),
                BilliardTable(
                    table_no='T002',
                    table_name='斯诺克桌1号',
                    table_type='snooker',
                    size='12ft',
                    brand='Riley',
                    area='B区',
                    floor=1,
                    position='中央位置',
                    hourly_rate=80.00,
                    member_rate=56.00,
                    peak_rate=100.00,
                    has_lighting=True,
                    has_scoreboard=True,
                    is_premium=True
                ),
                BilliardTable(
                    table_no='T003',
                    table_name='中式八球桌1号',
                    table_type='chinese_eight',
                    size='9ft',
                    brand='星牌',
                    area='A区',
                    floor=1,
                    position='角落位置',
                    hourly_rate=50.00,
                    member_rate=35.00,
                    peak_rate=70.00,
                    has_lighting=True,
                    has_scoreboard=False
                )
            ]
            
            for table in tables:
                db.session.add(table)
            
            print("正在创建测试工作人员...")
            staff = Staff(
                staff_no='S001',
                username='staff001',
                password='staff123',
                name='张小明',
                phone='13800138001',
                position='店员',
                department='服务部',
                hire_date=datetime.now()
            )
            db.session.add(staff)
            
            # 提交所有更改
            db.session.commit()
            print("数据库初始化完成！")
            
            print("\n默认账户信息：")
            print("管理员账户：admin / admin123")
            print("工作人员账户：staff001 / staff123")
            
        except Exception as e:
            print(f"初始化失败: {str(e)}")
            db.session.rollback()
            return False
            
    return True

if __name__ == '__main__':
    if init_database():
        print("数据库初始化成功！")
    else:
        print("数据库初始化失败！")